<template>
  <div class="draggable_content">
    <div class="header">
      <span>{{ props.title }}</span>
    </div>
    <div class="content">
      <el-tree
        v-if="data.myArray.length > 0"
        ref="treeRef"
        style="max-width: 600px"
        node-key="folderId"
        highlight-current
        :data="data.myArray"
        :props="defaultProps"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data: nodexData }">
          <div class="tree-node">
            <p>
              <img v-if="nodexData.parentId !== 0" :src="fileImg" alt="" />
              <span class="text-over" :title="nodexData.folderName" v-show="!nodexData.isEdit">{{ nodexData.folderName }}</span>
              <el-input
                v-show="nodexData.isEdit"
                ref="autoFocusL"
                size="small"
                maxlength="10"
                v-model.trim="nodexData.folderName"
                @click.stop
                @blur="handelBlur(nodexData)"
                @focus="onFocus"
                oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
              ></el-input>
            </p>

            <div @click.stop>
              <el-popover placement="bottom" title="" :width="200" trigger="hover" :popper-class="'template-actionmore'">
                <template #default>
                  <div class="action-wrap">
                    <p
                      v-for="(item, i) in nodexData.parentId === 0 ? data.operateList : data.operateListChildFile"
                      :key="i"
                      @click="handelClickOperate(nodexData, item)"
                    >
                      <el-button link :type="item.command === 'd' ? 'danger' : 'default'">{{ item.name }}</el-button>
                    </p>
                  </div>
                </template>
                <template #reference>
                  <!-- <img :src="more" alt="" /> -->
                  <span class="el-dropdown-link">
                    <el-icon><MoreFilled /></el-icon>
                  </span>
                </template>
              </el-popover>
            </div>
          </div>
        </template>
      </el-tree>
      <div v-else style="display: flex; justify-content: center; width: 100%">
        <el-empty description="暂无数据" />
      </div>
    </div>
    <div class="add_file">
      <!-- <el-button @click="setDefault">设置默认值</el-button> -->
      <el-button :icon="Plus" type="primary" @click="handelClickAddFile">新建文件夹</el-button>
    </div>
  </div>
</template>
<script setup>
// 资源导入
import { reactive, defineProps, defineEmits, onMounted, ref, nextTick } from "vue";
import draggable from "vuedraggable";
import { CaretBottom, CaretTop, Plus } from "@element-plus/icons-vue";
import fileImg from "@/static/images/folder.png";
import more from "@/static/images/more.png";
import move from "@/static/images/move.png";
import { ElMessage } from "element-plus";
import { findAncestorsById } from "@/utils";
// api
import { createFolder, filieList, deleteFolder, copyFolder } from "@/apis/createFile/index.js";
// 变量定义
const autoFocusL = ref();
const treeRef = ref();
const defaultProps = {
  children: "childFolder",
  label: "folderName"
};
const emits = defineEmits(["clickItem"]);
const props = defineProps({
  title: {
    type: String,
    default() {
      return "";
    }
  },
  saveLocalStore: {
    type: Function,
    default: null
  }
});
const data = reactive({
  // 选中的数据
  selectedData: {},
  num: -1,
  childNum: -1,
  // 拖动列表数据
  myArray: [],
  operateList: [
    { id: 1, name: "添加子文件", command: "a" },
    { id: 2, name: "编辑", command: "b" },
    { id: 3, name: "复制", command: "c" },
    { id: 4, name: "删除", command: "d" }
  ],
  operateListChildFile: [
    { id: 2, name: "编辑", command: "b" },
    { id: 3, name: "复制", command: "c" },
    { id: 4, name: "删除", command: "d" }
  ],
  engineeringTypeList: []
});

// 方法定义

const onFocus = event => {
  event.target.select();
  // console.log(909090, event);
};

const setDefault = folderId => {
  // 1831213894980440064 1830793142833614848
  treeRef.value?.setCurrentKey(folderId, true);
};

const currNode = ref({});
const handleNodeClick = node => {
  if (node.childFolder.length > 0) return;
  currNode.value = node;
  props.saveLocalStore && props.saveLocalStore();
  emits("clickItem", node);
  // console.log("点击了树节点", node);
};

const handelClickFirstFile = (item, index) => {
  console.log(item);
  // 是否打开当前项
  item.isExpand = !item.isExpand;
  // 赋值给选中的数据
  data.selectedData = item;
  data.num = index;
  data.myArray.map(it => {
    it.childFolder.map(cit => {
      cit.isActive = false;
    });
  });
};
// 新建文件
const handelClickAddFile = () => {
  createFolder({ showOrder: data.num == -1 ? data.myArray.length : data.num })
    .then(async res => {
      if (res.code === 200) {
        console.log(1);
        await getFilieList2();

        nextTick(() => {
          //创建成功之后，默认选中当前节点   1834796518089617408
          treeRef.value?.setCurrentKey(res.data, true);
          const currNode = treeRef.value.getCurrentNode();
          console.log("当前选中的树节点===", treeRef.value.getCurrentNode());
          handleNodeClick(currNode);
        });
      }
    })
    .catch(err => {
      console.log(err);
    });
};
// 获取文件列表
const getFilieList = async () => {
  await filieList().then(res => {
    // 给每一项添加属性，isExpand是否展开文件夹，isEdit是否编辑状态
    if (res.code == 200) {
      const List = JSON.parse(JSON.stringify(res.data));
      const firstLeafNode = findFirstLeafNode(List); //第一个叶子节点
      // res.data.map((it, i) => {
      //   // 第一项默认选中
      //   if (i == 0) {
      //     it.isExpand = true;
      //     it.isEdit = false;
      //     it.childFolder.map((cit, ci) => {
      //       if (ci == 0) {
      //         cit.isActive = true;
      //         cit.isEdit = false;
      //         // 这里进来第一项默认选中并获取数据
      //         handelClickChildItem(cit, ci);
      //       } else {
      //         cit.isActive = false;
      //         cit.isEdit = false;
      //       }
      //     });
      //   } else {
      //     it.isExpand = false;
      //     it.isEdit = false;
      //     it.childFolder.map(cit => {
      //       cit.isActive = false;
      //       cit.isEdit = false;
      //     });
      //   }
      // });
      data.myArray = res.data;

      nextTick(() => {
        // console.log("第一个叶子节点", firstLeafNode);

        const quotaAtore = JSON.parse(localStorage.getItem("quota"));
        const folderId1 = quotaAtore?.folderId1;
        if (folderId1) {
          //有缓存，设置默认值
          const arr = findAncestorsById(folderId1, List, "folderId", [], "childFolder") || [];
          // console.log("找到父级了", arr);
          if (arr.length > 0) {
            currNode.value = arr[arr?.length - 1];
            setDefault(folderId1); //选中缓存中的节点
            handelClickChildItem({ folderId: folderId1 }); //查询数据
          }
        } else {
          //没有缓存，存缓存
          setDefault(firstLeafNode.folderId); //默认选中第一个
          currNode.value = firstLeafNode;
          handelClickChildItem({ folderId: firstLeafNode.folderId }); //查询数据
          props.saveLocalStore && props.saveLocalStore();
        }
      });
    }
  });
};
const getFilieList2 = async () => {
  await filieList().then(res => {
    // 给每一项添加属性，isExpand是否展开文件夹，isEdit是否编辑状态
    if (res.code == 200) {
      const List = JSON.parse(JSON.stringify(res.data));
      data.myArray = List;
    }
  });
};

const findFirstLeafNode = tree => {
  // 定义递归函数 traverse，用于深度搜索树的每个节点
  function traverse(node) {
    // 如果当前节点为叶子节点，即没有子节点，则返回该节点
    if (!node.childFolder || node.childFolder.length === 0) {
      return node;
    }
    // 如果当前节点有子节点，则遍历每个子节点，继续递归调用 traverse 函数
    for (const child of node.childFolder) {
      const result = traverse(child);
      // 如果在子节点中找到了第一个叶子节点，则立即返回该节点
      if (result) {
        return result;
      }
    }
  }

  // 外部循环遍历树的根节点
  for (const node of tree) {
    // 对于每个根节点，都调用 traverse 函数来查找第一个叶子节点
    const result = traverse(node);
    // 如果在当前根节点下找到了第一个叶子节点，则立即返回该节点
    if (result) {
      return result;
    }
  }
  return null;
};
// 更多操作
const handelClickOperate = (element, item) => {
  const command = item.command;
  if (command === "b") {
    element.isEdit = true;
  } else if (command === "a") {
    createFolder({ parentId: element.folderId, showOrder: data.myArray.length }).then(async res => {
      if (res.code === 200) {
        await getFilieList();

        nextTick(() => {
          //创建成功之后，默认选中当前节点   1834796518089617408
          treeRef.value?.setCurrentKey(res.data, true);
          const currNode = treeRef.value.getCurrentNode();
          // console.log("当前选中的树节点===", res.data, treeRef.value.getCurrentNode());
          handleNodeClick(currNode);
        });
      }
    });
  } else if (command === "d") {
    const currNode = treeRef.value.getCurrentNode();

    // return;

    deleteFolder(element.folderId)
      .then(async () => {
        console.log("删除成功");
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        await getFilieList();

        nextTick(() => {
          if (currNode.folderId === element.folderId) {
            // 删除高亮状态下的树节点
            console.log("正在删除当前高亮的树节点");
            if (element.parentId === 0) {
              // 是一级根节点。删除成功之后，默认选中第一个根节点
              const List = JSON.parse(JSON.stringify(data.myArray));
              const firstLeafNode = findFirstLeafNode(List); //第一个叶子节点
              treeRef.value?.setCurrentKey(firstLeafNode.folderId, true);
            } else {
              //是二级子节点。删除成功之后，默认选中当前根节点下面的第一个子节点
              const obj = data.myArray.find(item => item.folderId === element.parentId);
              const arrs = obj.childFolder || [];
              console.log("兄弟节点===", arrs);
              if (arrs.length > 0) {
                treeRef.value?.setCurrentKey(arrs[0].folderId, true);
              } else {
                treeRef.value?.setCurrentKey(element.parentId, true);
              }
            }

            //模拟点击查询数据
            const currNode = treeRef.value.getCurrentNode();
            handleNodeClick(currNode);
          } else if (element.parentId === 0) {
            // 删除一级根节点。删除成功之后，默认选中第一个根节点
            const List = JSON.parse(JSON.stringify(data.myArray));
            const firstLeafNode = findFirstLeafNode(List); //第一个叶子节点
            treeRef.value?.setCurrentKey(firstLeafNode.folderId, true);
          }
        });
      })
      .catch(err => {
        console.log(err);
      });
  } else if (command === "c") {
    copyFolder(element.folderId).then(() => {
      ElMessage({
        type: "success",
        message: "复制成功"
      });
      getFilieList();
    });
  }
  console.log(element);
};
// 失去焦点时保存当前文件的名称并不让在编辑
const handelBlur = element => {
  createFolder(element).then(res => {
    // getFilieList();
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "编辑成功"
      });

      element.isEdit = false;
    }
  });
};
const handelClickChildItem = (item, i) => {
  // console.log(item, i);
  // data.num = -1;
  // data.childNum = i;
  // item.isActive = true;
  // data.myArray.map(it => {
  //   it.childFolder.map(cit => {
  //     cit.isActive = false;
  //     if (cit.folderId === item.folderId) {
  //       cit.isActive = true;
  //     }
  //   });
  // });
  emits("clickItem", item);
};
// 生命周期
onMounted(() => {
  getFilieList();
});
defineExpose({ currNode });
// 监听
</script>

<style lang="scss">
.template-actionmore {
  min-width: auto !important;
  width: 120px !important;
  border-radius: 6px !important;
  box-sizing: border-box !important;
  .el-button {
    width: 100%;
    justify-content: flex-start !important;
    line-height: 26px !important;
    font-size: 12px !important;
  }

  .action-wrap {
    .el-button.el-button--default.is-link {
      &:hover {
        color: #007dff;
      }
    }
    .el-button.el-button--danger.is-link {
      &:hover {
        color: red;
      }
    }
  }
}
</style>
<style scoped lang="scss">
:deep(.el-dropdown-link) {
  margin-right: 10px;
  display: flex;
  height: 16px;
  & > i {
    transform: rotate(90deg);
  }
}
:deep(.el-tree-node__content) {
  --el-tree-node-content-height: 44px;
}
:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  --el-color-primary-light-9: #d9e8ff !important;
  color: #007dff !important;
}
:deep(.el-tree) {
  width: 100%;
  overflow-x: auto;
  // padding-bottom: 94px;

  .el-icon.el-tree-node__expand-icon {
    padding-left: 10px;
  }
  .el-tree-node__content {
    line-height: 44px;
    height: 44px;
    .tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .el-input__wrapper {
        line-height: 32px;
        height: 32px;
      }
      img {
        margin-right: 10px;
      }
      & > p {
        display: flex;
        align-items: center;
        span {
          display: inline-block;
          flex: 1;
          max-width: 100px;
        }
      }
    }
  }
}
.active {
  background-color: #d9e8ff !important;
}
.active1 {
  background-color: #d9e8ff !important;
}
.file_operate {
  display: flex;
  justify-content: space-between;
  width: 100%;
  &_right {
    display: flex;
    align-items: center;
  }
}
.draggable_content {
  // padding: 20px;
  width: 282px;
  height: calc(100% - 0px);
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  .header {
    font-size: 18px;
    color: #131414;
    // padding: 20px;
    overflow: hidden;
    padding: 20px 20px 0 20px;
    span::before {
      content: "";
      width: 6px;
      height: 6px;
      position: absolute;
      left: -14px;
      background-color: #409eff;
      top: 50%;
      transform: translate(-50%, -50%);
      border-radius: 50%;
    }
    span {
      margin-left: 20px;
      position: relative;
    }
  }
}
// 拖拽外层内容css
.content {
  margin-top: 20px;
  height: calc(100% - 160px);
  overflow-y: auto;
  // overflow: scroll;
}
.file {
  width: 100%;
  height: 44px;
  display: flex;
  align-items: center;
  cursor: pointer;
  box-sizing: border-box;
  img {
    width: 16px;
    vertical-align: middle;
  }
  span {
    // margin-left: 10px;
  }
}
.child_file {
  padding-left: 62px;
  overflow: hidden;
  width: 100%;
  height: 44px;
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #000;
  box-sizing: border-box;
  span {
    margin-left: 10px;
  }
  img {
    width: 16px;
  }
}
.add_file {
  height: 92px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}
</style>
